package org.zhuzx.util.spring;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

public class MemoryMultipartFile implements MultipartFile {

	private String filename;
	private byte[] bytes;
	private InputStream in;
	private String name;
	private String contentType;
	
	public MemoryMultipartFile(String filename, byte[] bytes) {
		this.filename = filename;
		this.bytes = bytes;
		this.in = new ByteArrayInputStream(bytes);
	}
	
	@Override
	public String getName() {
		return name;
	}

	@Override
	public String getOriginalFilename() {
		return filename;
	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public boolean isEmpty() {
		return bytes.length == 0;
	}

	@Override
	public long getSize() {
		return bytes.length;
	}

	@Override
	public byte[] getBytes() throws IOException {
		return bytes;
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return in;
	}

	@Override
	public void transferTo(File dest) throws IOException, IllegalStateException {
		FileOutputStream out = new FileOutputStream(dest);
		out.write(bytes);
		out.close();
	}
	
	public void setName(String name) {
		this.name = name;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

}